package com.lottery.im.module.setting.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.Api;
import com.lottery.im.api.result.entity.UserInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.chat.ui.ModifySingleTextFragment;
import com.lottery.im.module.setting.presenter.SettingPresenter;
import com.lottery.im.module.setting.view.SettingView;
import com.lottery.im.util.DisplayHelper;
import com.lottery.im.util.SPUtils;
import com.lottery.im.util.StatusBarHelper;
import com.lottery.im.util.transformations.CropCircleTransformation;
import com.lottery.im.widget.ShSwitchView;
import com.lottery.im.widget.dialog.BottomSelectDialog;
import com.lottery.im.widget.dialog.ConfirmWarnDialogBuilder;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.imsdk.TIMFriendGenderType;
import com.tencent.imsdk.TIMUserProfile;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import java.util.ArrayList;

/*
 * 设置
 * */
public class SettingFragment extends BaseSwipeFragment<SettingPresenter> implements SettingView {

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.iv_portrait) ImageView mIvPortrait;
  @BindView(R.id.tv_name) TextView mTvName;
  @BindView(R.id.tv_sex) TextView mTvSex;
  @BindView(R.id.sw_open_yz) ShSwitchView mSwOpenYz;
  @BindView(R.id.sw_open_tz) ShSwitchView mSwOpenTz;

  private TIMUserProfile mTIMUserProfile;

  // 拍照
  private final static int PICK_PHOTO_REQCODE = 88;
  // 图片选择
  private final static int PICK_IMAGE_REQCODE = 888;
  // 修改昵称
  private final static int NICKNAME_REQCODE = 8888;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_setting;
  }

  @Override protected void initPresenter() {
    presenter = new SettingPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    StatusBarHelper.setStatusBarDarkMode(getActivity());
    UserInfo userInfo = MyApplication.getInstance().getUserInfo();
    Glide.with(this)
        .load(Api.BASEADDRESS + userInfo.getUserPic())
        .apply(new RequestOptions()
            .bitmapTransform(new CropCircleTransformation())
            .placeholder(R.drawable.icon_conversation_de)
            .error(R.drawable.icon_conversation_de))
        .into(mIvPortrait);
    mTvTitle.setText(getString(R.string.set));
    mTvName.setText(userInfo.getUserName());

    boolean isNotify = (boolean) SPUtils.get(mActivity, SpKeyConstant.MESSAGE_NOTIFY_KEY, true);
    String notifyId = (String) SPUtils.get(mActivity, SpKeyConstant.MESSAGE_NOTIFY_ID_KEY, "");
    if (notifyId.equals(MyApplication.getInstance().getUserInfo().getUserId())) {
      mSwOpenTz.setOn(isNotify);
    } else {
      mSwOpenTz.setOn(true);
    }
    mSwOpenTz.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
      @Override public void onSwitchStateChange(boolean isOn) {
        SPUtils.put(mActivity, SpKeyConstant.MESSAGE_NOTIFY_KEY, isOn);
        SPUtils.put(mActivity, SpKeyConstant.MESSAGE_NOTIFY_ID_KEY,
            MyApplication.getInstance().getUserInfo().getUserId());
      }
    });

    boolean isEquipment = (boolean) SPUtils.get(mActivity, SpKeyConstant.IS_EQUIPMENT_KEY, false);
    String equipmentId = (String) SPUtils.get(mActivity, SpKeyConstant.IS_EQUIPMENT_ID_KEY, "");
    if (equipmentId.equals(MyApplication.getInstance().getUserInfo().getUserId())) {
      mSwOpenYz.setOn(isEquipment);
    } else {
      mSwOpenYz.setOn(false);
    }

    mSwOpenYz.setOnSwitchStateChangeListener(mOnSwitchStateChangeListener);

    presenter.getSelfProfile();
  }

  @OnClick({
      R.id.iv_back, R.id.layout_portrait, R.id.layout_name, R.id.layout_sex, R.id.layout_login_pwd,
      R.id.layout_ver_pwd, R.id.layout_money_pwd
  }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.layout_portrait:
        new BottomSelectDialog().create(getActivity(), "请选择打开方式", "相机", "相册",
            v -> {
              openPickImage(1);
              BottomSelectDialog.dismiss();
            }, v -> {
              openPickImage(2);
              BottomSelectDialog.dismiss();
            }).show();
        break;
      case R.id.layout_name:
        startFragmentForResult(
            ModifySingleTextFragment.create("", mTvName.getText().toString(),
                ModifySingleTextFragment.OpType.NICKNAME),
            NICKNAME_REQCODE);
        break;
      case R.id.layout_sex:
        new BottomSelectDialog().create(getActivity(), "请选择性别", "男", "女",
            v -> {
              setSex(1);
              BottomSelectDialog.dismiss();
            }, v -> {
              setSex(2);
              BottomSelectDialog.dismiss();
            }).show();
        break;
      case R.id.layout_login_pwd:
        startFragment(new ChangeLoginPwdFragment());
        break;
      case R.id.layout_ver_pwd:
        startFragment(new AddVerPwdFragment());
        //if ("1".equals(MyApplication.getInstance().getUserInfo().getPwdInfo())) {
        //  startFragment(new ChangeVerPwdFragment());
        //} else {
        //  startFragment(new AddVerPwdFragment());
        //}
        break;
      case R.id.layout_money_pwd:
        if ("Y".equals(MyApplication.getInstance().getUserInfo().getIsSetPayPwd())) {
          startFragment(new ChangeMoneyPwdFragment());
        } else {
          startFragment(new AddMoneyPwdFragment());
        }
        break;
    }
  }

  ShSwitchView.OnSwitchStateChangeListener mOnSwitchStateChangeListener =
      new ShSwitchView.OnSwitchStateChangeListener() {
        @Override public void onSwitchStateChange(boolean isOn) {
          if (isOn && "0".equals(MyApplication.getInstance().getUserInfo().getPwdInfo())) {
            new Handler().postDelayed(() -> mSwOpenYz.setOn(false), 400);

            ConfirmWarnDialogBuilder.getInstance(mActivity).setContent("请先设置验证密码")
                .setCancel("取消", null)
                .setConfirm("去设置", v -> startFragment(new AddVerPwdFragment()))
                .show();
          } else {
            SPUtils.put(mActivity, SpKeyConstant.IS_EQUIPMENT_KEY, isOn);
            SPUtils.put(mActivity, SpKeyConstant.IS_EQUIPMENT_ID_KEY,
                MyApplication.getInstance().getUserInfo().getUserId());
          }
        }
      };

  /**
   * 打开图片选择
   *
   * @param type 1 相机 2 相册
   */
  private void openPickImage(int type) {

    new RxPermissions(getActivity()).request(Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE)
        .subscribe(new Observer<Boolean>() {
          @Override public void onSubscribe(Disposable d) {
          }

          @Override public void onNext(Boolean aBoolean) {
            if (aBoolean) {
              int screenWidth = DisplayHelper.getScreenWidth(mActivity);
              ImagePicker.getInstance().setMultiMode(false);
              ImagePicker.getInstance().setCrop(true);
              ImagePicker.getInstance().setStyle(CropImageView.Style.CIRCLE);
              ImagePicker.getInstance().setFocusWidth(screenWidth / 3 * 2);
              ImagePicker.getInstance().setFocusHeight(screenWidth / 3 * 2);
              if (type == 1) {
                Intent intent = new Intent(mActivity, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, PICK_PHOTO_REQCODE);
              } else if (type == 2) {
                ImagePicker.getInstance().setShowCamera(false);  //显示拍照按钮
                Intent intent = new Intent(mActivity, ImageGridActivity.class);
                startActivityForResult(intent, PICK_IMAGE_REQCODE);
              }
            } else {
              showToast("你已拒绝访问相册和拍照权限～");
            }
          }

          @Override public void onError(Throwable e) {

          }

          @Override public void onComplete() {

          }
        });
  }

  /**
   * 修改性别
   *
   * @param type 1 男 2女
   */
  private void setSex(int type) {
    presenter.setSex(type);
  }

  /**
   * 获取的用户本身IM资料
   */
  @Override public void getSelfProfileSuce(TIMUserProfile timUserProfile) {
    mTIMUserProfile = timUserProfile;
    if (mTIMUserProfile.getGender() == TIMFriendGenderType.Female) {
      mTvSex.setText("女");
    } else if (mTIMUserProfile.getGender() == TIMFriendGenderType.Male) {
      mTvSex.setText("男");
    } else {
      mTvSex.setText("");
    }
  }

  @Override public void updateFaceUrl(String url) {
    UserInfo userInfo = MyApplication.getInstance().getUserInfo();
    userInfo.setUserPic(url);
    UserInfo.refreshInfo(mActivity, userInfo);
    Glide.with(this)
        .load(Api.BASEADDRESS + userInfo.getUserPic())
        .apply(new RequestOptions()
            .bitmapTransform(new CropCircleTransformation())
            .placeholder(R.drawable.icon_conversation_de)
            .error(R.drawable.icon_conversation_de))
        .into(mIvPortrait);
  }

  @Override public void setSexSuc(int type) {
    if (type == 1) {
      mTvSex.setText("男");
    } else {
      mTvSex.setText("女");
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      if (requestCode == PICK_IMAGE_REQCODE || requestCode == PICK_PHOTO_REQCODE) {
        // 选择图片、拍照完成
        ArrayList<ImageItem> images =
            (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        presenter.uploadUserHeadImg(images.get(0).path);
      }
    }
  }

  @Override protected void onFragmentResult(int requestCode, int resultCode, Intent data) {
    super.onFragmentResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
      if (requestCode == NICKNAME_REQCODE && null != data) {
        mTvName.setText(data.getStringExtra(ModifySingleTextFragment.INPUT_CONTENT_KEY));
      }
    }
  }

  @Override public void onResume() {
    super.onResume();
    StatusBarHelper.setStatusBarDarkMode(getActivity());
  }
}
